package main

import (
	"embed"
	"gotransfer/controller"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/gin-gonic/gin"
)

//go:embed static/*
var staticFS embed.FS

func main() {
	gin.SetMode(gin.ReleaseMode)

	r := gin.New()
	// 自定义日志中间件
	r.Use(func(c *gin.Context) {
		log.Printf("Request URL: %s", c.Request.URL.String())
		c.Next()
	})

	// 使用嵌入的文件系统来提供静态文件服务
	staticHandler := http.FileServer(http.FS(staticFS))
	r.GET("/static/*filepath", func(c *gin.Context) {
		// 去除 "/static" 前缀
		_ = c.Param("filepath")
		// 从嵌入的文件系统中读取文件
		staticHandler.ServeHTTP(c.Writer, c.Request)
	})
	// 定义一个路由来访问 index.html
	r.GET("/", func(c *gin.Context) {
		htmlContent, err := staticFS.ReadFile("static/index.html")
		if err != nil {
			c.String(http.StatusInternalServerError, "打开首页index.html失败: %v", err)
			return
		}
		c.Data(http.StatusOK, "text/html; charset=utf-8", htmlContent)
	})

	// 文件上传
	r.POST("/upload", controller.UploadHandler)
	// 文件下载
	r.GET("/download/:filename", controller.DownloadHandler)
	// 列出已上传文件
	r.GET("/list-files", controller.ListFilesHandler)

	log.Println("服务器已启动，地址为 http://localhost:8080")

	// Set up a timer to stop the server after 5 minutes
	go func() {
		time.Sleep(5 * time.Minute)
		log.Println("服务器已经运行5分钟，即将关闭...")
		os.Exit(0)
	}()

	if err := r.Run(":8080"); err != nil {
		log.Fatalf("启动服务器时出错: %v", err)
	}
}
